import { useEffect, useState } from 'react'
import { nanoid } from 'nanoid'
// import { message } from 'antd'
import { useRecoilValue } from 'recoil'
import { message } from 'antd'
import { useNavigate } from 'react-router-dom'
import { formConfigType } from '../interface/index'
import { dict, uploadingFile, platformApplyFor } from '../service/index'
import { platformDetailsInfo } from '@/store/platformDetails'
import { isNullData } from '@/utils'

export default () => {
  // recoil 读取出来的对象
  const user: any = useRecoilValue(platformDetailsInfo)

  const routerPush = useNavigate()

  // 医院定级
  const [hospitalRank, setHospitalRank] = useState([])
  // 医院定等
  const [hospitalRated, setHospitalRated] = useState([])
  // 是否教学医院
  const [yesNoHospital, setYesNoHospital] = useState([])
  // 医院性质
  const [hospitalNature, setHospitalNature] = useState([])
  // 医院类别
  const [hospitalType, setHospitalType] = useState([])
  // 上传文件数组，判断 Form 校验
  const [uploadFileArray, setUploadFileArray] = useState([])
  // 存储要发给后端的文件后缀名字
  const [fileName, setFileName] = useState('')
  // 存储文件的中文名字
  const [fileFontName, setFileFontName] = useState<string>('')

  const onFinish = async (value: any) => {
    // console.log('🦢🦢', user.platformId)
    if (uploadFileArray.length === 0) {
      message.error('请上传文件!')
      return
    }
    console.log(value.hospitalArea)

    // return
    //  telphone 护理部电话
    value.telphone = `${value.areaCode}-${value.phone}`
    // value.hospitalArea = 12 // 医院所在地，后端暂时还没返数据 []
    value.hospitalArea = value.hospitalArea.join(',') // 医院所在地
    value.promiseBook = fileName // 上传之后的文件名字,res
    value.platformId = user.platformId
    value.promiseBookOriginalFileName = fileFontName
    console.log('提交完毕之后的所有数据🦢🦢', value)

    // return
    const res = await platformApplyFor(value)
    if (isNullData(res) && res.data.status) {
      message.success('已提交申请!')
      routerPush('/user/login')
    } else {
      message.error(res.data.msg)
    }
    // console.log(res)
  }

  // 校验医院名称字符数量
  const validateTextLength = (_: object, value: string) => {
    if (!value) {
      return Promise.reject('请填写医院名称!')
    }
    if (value && value.length > 100) {
      return Promise.reject('文本长度不能超过100个字符!')
    }
    return Promise.resolve()
  }
  // 校验统一社会信用代码
  const validateTongyixinyong = (_: object, value: string) => {
    if (!value) {
      return Promise.reject('请输入统一社会信用代码!')
    }
    const pattern = /^[a-zA-Z0-9]+$/
    if (value && !pattern.test(value)) {
      return Promise.reject('只能输入数字或字母,不允许空格!')
    }
    if (value.length < 18) {
      return Promise.reject('请输入18位统一社会信用代码!')
    }
    return Promise.resolve()
  }
  // 校验编制床位数
  const validateBedNumber = (_: object, value: string) => {
    if (!value) {
      return Promise.reject('请输入编制床位数!')
    }
    const parsedValue = parseInt(value, 10)
    if (
      Number.isNaN(parsedValue) ||
      !Number.isInteger(parsedValue) ||
      parsedValue < 0 ||
      parsedValue > 5000 ||
      value.includes('.')
    ) {
      return Promise.reject('请输入大于等于 0 且不大于 5000 的整数!')
    }

    return Promise.resolve()
  }
  // 校验注册护士数
  const validateNurseNumber = (_: object, value: string) => {
    if (!value) {
      return Promise.reject('请输入注册护士数!')
    }

    const parsedValue = parseInt(value, 10)

    if (
      Number.isNaN(parsedValue) ||
      !Number.isInteger(parsedValue) ||
      parsedValue < 0 ||
      parsedValue > 5000 ||
      value.includes('.')
    ) {
      return Promise.reject('请输入大于等于 0 且不大于 5000 的整数!')
    }

    return Promise.resolve()
  }
  // 校验区号
  const validateAreaCode = (_: object, value: string) => {
    if (!value) {
      return Promise.reject('请输入区号!')
    }
    const pattern = /^\d{3,4}$/
    if (!pattern.test(value)) {
      return Promise.reject('请输入三到四位数字的区号!')
    }
    return Promise.resolve()
  }
  // 校验区号后面的号码
  const validateAreaCodePhone = (_: object, value: string) => {
    if (!value) {
      return Promise.reject('请输入电话号码!')
    }
    const pattern = /^\d{7,8}$/
    if (!pattern.test(value)) {
      return Promise.reject('请输入7到8位数字号码!')
    }
    return Promise.resolve()
  }
  // 过滤字典字段函数封装
  const transformData = (data: any, key: any) => {
    const obj = data.find((item: any) => Object.keys(item)[0] === key)
    if (!obj) return []

    const array = obj[key]
    return array.map((item: any) => ({
      value: item.value,
      name: item.label,
      id: nanoid(),
    }))
  }
  // 获取字典
  const getDict = async () => {
    const res = await dict()

    const transformedHospitalLevel = transformData(res.data, 'hospital_level')
    setHospitalRank(transformedHospitalLevel)
    const transformedHospitalRating = transformData(res.data, 'hospital_rating')
    setHospitalRated(transformedHospitalRating)
    const transformedIsTeachHospital = transformData(res.data, 'is_teach_hospital')
    setYesNoHospital(transformedIsTeachHospital)
    const transformedHospitalNature = transformData(res.data, 'hospital_nature')
    setHospitalNature(transformedHospitalNature)
    const transformedHospitalType = transformData(res.data, 'hospital_type')
    setHospitalType(transformedHospitalType)
  }

  // 上传文件
  const handleFileUpload = async ({ file }: any) => {
    // 限制不能上传超过 5 mb 的文件
    const fileSizeLimit = 5 * 1024 * 1024
    if (file.size > fileSizeLimit) {
      message.error('文件大小超过限制！请上传不超过 5MB 的文件。')
      return
    }
    // 执行文件上传逻辑
    const formData = new FormData()
    formData.append('file', file)
    const res = await uploadingFile(formData, 'uploadFile')
    if (isNullData(res)) {
      message.success('上传成功!')
      // 存放后端要的文件后缀名字
      setFileName(res.data.sysPath.split('/')[1])
      // 存放后端要的文件中文名字
      setFileFontName(res.data.originalFileName)
      // 存数组，做判断
      const copyUploadFileArray: any = []
      copyUploadFileArray.push(res.data)
      setUploadFileArray(copyUploadFileArray)
    }
  }

  useEffect(() => {
    getDict()
  }, [])

  // useEffect(() => {
  //   console.log(uploadFileArray)
  // }, [uploadFileArray])

  const formConfig: formConfigType = {
    validateTextLength,
    validateTongyixinyong,
    validateBedNumber,
    validateNurseNumber,
    onFinish,
    handleFileUpload,
    validateAreaCode,
    validateAreaCodePhone,
    hospitalRank,
    hospitalRated,
    yesNoHospital,
    hospitalNature,
    hospitalType,
    uploadFileArray,
  }
  return {
    formConfig,
  }
}
